<?php

namespace Beerus\Modules\BrandRights\Controllers;

use App\Http\Controllers\Controller;
use App\Pockets\GridDataModel;
use Biz\model\brand\Brand;
use Biz\model\brand\BrandPackage;
use Biz\model\brandAccount\BrandAccountInfo;
use Biz\model\brandRights\BrandLevelRightsConfig;
use Biz\model\brandRights\BrandRightsAll;
use Biz\model\brandRights\BrandRightsSource;
use Biz\service\BrandRights\BrandEquityVerificationService;
use Biz\service\BrandRights\BrandRightsAllService;
use Biz\service\BrandRights\BrandRightsSourceService;
use Biz\tools\helper\Common;
use Doctrine\DBAL\Exception;
use Doraemon\pockets\datebase\BaseDbModel;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Grid;
use Encore\Admin\Grid\Displayers\Actions;
use Encore\Admin\Layout\Content;
use Encore\Admin\Widgets\Form;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\MessageBag;

class BrandSourceController extends Controller
{
    public const  PAGE_SIZE = 20;

    /**
     * 获取列表
     * @param Request $request
     * @param Content $content
     * @return Content
     */
    public function index(Request $request, Content $content): Content
    {
        $params = $request->all();
        $page_size = $params['per_page'] ?? self::PAGE_SIZE;
        $params['per_page'] = $page_size;
        $where = $this->_getWhere($params);
        $where['pack_type[>]'] = 0;
        $where['status'] = BaseDbModel::STATUS_NORMAL;
        $list = Brand::selectByWhere($where, ['id', 'brand_name', 'pack_type']);
        $packTypes = array_column($list, 'pack_type');
        $packTypes = array_unique($packTypes);
        $packList = BrandPackage::select_master(['package_name', 'pack_type'], ['pack_type' => $packTypes]);
        $packList = array_column($packList, 'package_name', 'pack_type');
        foreach ($list as &$item) {
            $item['package_name'] = $packList[$item['pack_type']] ?? '未知';
        }
        unset($where['LIMIT']);
        $count = Brand::count($where);
        $gridModel = new GridDataModel($list, $count, [
            'perPage' => $page_size,
        ]);
        $grid = Admin::grid($gridModel,
            function (Grid $grid) use ($gridModel) {
                $grid->paginate($gridModel->getPerPage());
                $grid->disableCreateButton();
                $grid->filter(function ($filter) {
                    $filter->disableIdFilter();
                    $filter->column(1 / 3, function ($filter) {
                        $filter->equal('brand_id', '品牌id');
                        $filter->expand();//默认展开
                    });

                });
                $grid->disableExport();
                $grid->disableRowSelector();
                $grid->column('id', 'ID');
                $grid->column('brand_name', '品牌名称');
                $grid->column('package_name', '套餐');
                $grid->setActionClass(Actions::class);
                $grid->actions(function (Grid\Displayers\Actions $actions) {
                    $actions->disableEdit();
                    $actions->disableDelete();
                });
            }
        );
        $content->row($grid);

        return $content
            ->header('权益品牌列表')
            ->description(' ')
            ->breadcrumb(['text' => '权益品牌列表']);
    }


    /**
     * 获取查询条件
     * @param $params
     * @return array
     */
    private function _getWhere($params): array
    {
        $page = $params['page'] ?? 1;
        $per_page = $params['per_page'] ?? self::PAGE_SIZE;
        $brand_id = $params['brand_id'] ?? '';
        $where['LIMIT'] = [
            ($page - 1) * $per_page,
            $per_page,
        ];
        if ($brand_id) {
            $where['id'] = $brand_id;
        }
        if (isset($params['_sort']["column"], $params['_sort']["type"])) {
            $where['ORDER'] = [
                $params['_sort']["column"] => strtoupper($params['_sort']["type"]),
            ];
        }
        return $where;
    }

    /**
     * 查看
     * @param $brandId
     * @param Content $content
     * @return Content
     */
    public function view($brandId, Content $content): Content
    {
        Admin::script($this->auditScript());
        $list = BrandRightsAllService::getBrandsSourceList($brandId);
        $list = $list ? $list[$brandId] : [];
        $gridModel = new GridDataModel($list, 0, []);
        $grid = Admin::grid($gridModel,
            function (Grid $grid) use ($gridModel) {
                $grid->disablePagination();
                $grid->disableFilter();
                $grid->disableExport();
                $grid->disableRowSelector();
                $grid->column('id', 'ID');
                $grid->column('rights_title', '权益名称');
                $grid->column('rights_name', '权益英文名称')->copyable();
                $grid->column('total_num', '总量')->display(function ($total_num) {
                    if ($this->rights_type == BrandRightsSource::RIGHTS_TYPE_LIMIT_NUM ||
                        $this->rights_type == BrandRightsSource::RIGHTS_TYPE_NUM) {
                        return $total_num;
                    } else {
                        return '/';
                    }
                });
                $grid->column('rights_num', '可用数量')->display(function ($rights_num) {
                    if ($this->rights_type == BrandRightsSource::RIGHTS_TYPE_LIMIT_NUM ||
                        $this->rights_type == BrandRightsSource::RIGHTS_TYPE_NUM) {
                        return $rights_num;
                    } else {
                        return '/';
                    }
                });
                $grid->column('rights_type', '权益类型')->using(
                    BrandRightsSource::RIGHTS_TYPE_ARR
                    , '未知')->label([
                    BrandRightsSource::RIGHTS_TYPE_OPEN => 'warning',
                    BrandRightsSource::RIGHTS_TYPE_LIMIT_NUM => 'info',
                    BrandRightsSource::RIGHTS_TYPE_NUM => 'success',
                    BrandRightsSource::RIGHTS_TYPE_OTHER => 'default',
                ]);


                $grid->column('start_time', '开始时间');
                $grid->column('end_time', '结束时间');
                $grid->column('rights_status', '权益状态')->using(
                    BrandRightsAll::STATUS_ARR
                    , '未知')->label([
                    BrandRightsSource::STATUS_ON => 'success',
                    BrandRightsSource::STATUS_DELETE => 'danger',
                ]);
                $grid->disableActions();
                /*
                $grid->setActionClass(Actions::class);
                $grid->actions(function (Grid\Displayers\Actions $actions) {
                    $actions->disableEdit();
                    $actions->disableDelete();
                    $actions->disableView();
                    $html_pass = ' <a class="fa edit-pass-data" data-state="' . BrandRightsAll::STATUS_ON . '" data-id="' . $actions->row->id . '" href="javascript:void(0);">
                                    <span class="glyphicon glyphicon-ok" aria-hidden="true">开启</span></a>';
                    $html_unpass = '<a class="fa edit-pass-data" data-state="' . BrandRightsAll::STATUS_DELETE . '" data-id="' . $actions->row->id . '" href="javascript:void(0);">
                                    <span class="glyphicon glyphicon-remove" aria-hidden="true">关闭</span></a>';

                    if ($actions->row->rights_status == BrandRightsAll::STATUS_ON) {
                        $actions->prepend($html_unpass);
                    } else {
                        $actions->prepend($html_pass);
                    }
                });*/
            }
        );
        $content->row($grid);

        return $content
            ->header('品牌拥有权益信息')
            ->description(' ')
            ->breadcrumb(
                ['text' => '权益品牌列表', 'url' => '/BrandRights/brandSource'],
                ['text' => '品牌拥有权益信息']
            );
    }

    /**
     * 创建
     * @param $id
     * @param Form $form
     * @param Content $content
     * @return Content|RedirectResponse
     */
    public function create($id, Form $form, Content $content)
    {
        if (!$id) {
            admin_warning('参数错误！', 'warning');
            return back();
        }
        $accountInfo = BrandAccountInfo::getOneByWhere([
            'type' => BrandAccountInfo::ACCOUNT_TYPE_BRAND,
            'brand_id' => $id,
            'account_status' => BrandAccountInfo::ACCOUNT_STATUS_USED
        ], ['id', 'in_start_time', 'in_end_time'],
        );
        if ($accountInfo['in_end_time'] < date('Y-m-d')) {
            admin_warning('账户过期或不存在的品牌账户！', 'warning');
            return back();
//            throw new \Exception('账户过期或不存在的品牌账户!');
        }

        $brandInfo = Brand::getInfo($id);
        if (!$brandInfo) {
            admin_warning('不存在的品牌信息或品牌入驻时间无效！', 'warning');
            return back();
//            throw new \Exception('不存在的品牌信息或品牌入驻时间无效');
        }

        $form->text('id', '品牌id')->default($id)->readonly();

        $form->select('rights_type', '权益类型')->options(BrandRightsSource::RIGHTS_TYPE_ARR)
            ->when(BrandRightsSource::RIGHTS_TYPE_OPEN, function (Form $baseForm) {
                //开关型
                $where['rights_type'] = BrandRightsSource::RIGHTS_TYPE_OPEN;
                $option = $this->getItem($where);
//                $baseForm->text('num', '添加次数')->default(0)
//                    ->help("内容认领，设为精选需要填写数量!,其他开关型忽略");
                $baseForm->select('rights_id', '权益名称')->options($option);
            })->when(BrandRightsSource::RIGHTS_TYPE_LIMIT_NUM, function (Form $baseForm) {
                //消耗型
                $where['rights_type'] = BrandRightsSource::RIGHTS_TYPE_LIMIT_NUM;
                $option = $this->getItem($where);
                $baseForm->select('rights_id', '活动权益')->options($option);
                $baseForm->text('num', '添加次数')->setWidth(4)->default(1)->help("无穷则填写: 99999");
            })->when(BrandRightsSource::RIGHTS_TYPE_NUM, function (Form $baseForm) {
                //数量型
                $where['rights_type'] = BrandRightsSource::RIGHTS_TYPE_NUM;
                $option = $this->getItem($where);
                $baseForm->select('rights_id', '权益名称')->options($option);
                $baseForm->text('num', '设置数量')->setWidth(4)->default(1)->help("无穷则填写: 99999；权益则最终数量 = 当前输入 + 等级权益数量");
            })->when(BrandRightsSource::RIGHTS_TYPE_OTHER, function (Form $baseForm) {
                //其他
                $where['rights_type'] = BrandRightsSource::RIGHTS_TYPE_OTHER;
                $option = $this->getItem($where);
//                $baseForm->text('num', '添加次数')->default(0)
//                    ->help("内容认领，设为精选需要填写数量!,其他开关型忽略");
                $baseForm->select('rights_id', '权益名称')->options($option);
            })->required();

        $form->text('desc', '添加理由')->required();

        $form->confirm('确认要添加权益吗？');
        $form->action('/admin/BrandRights/brandSource/save');

        return $content
            ->header('增加权益')
            ->description(' ')
            ->breadcrumb(
                ['text' => '品牌权益信息', 'url' => '/BrandRights/brandSource/' . $id],
                ['text' => '增加权益']
            )
            ->row($form);

    }

    private function getItem($where): array
    {
        $option = BrandRightsSourceService::getAllSource(['id', 'rights_title'], $where);
        return $option ? array_column($option, 'rights_title', 'id') : [];
    }

    /*
     * 保存
     * @param Request $request
     * @throws \Exception
     */
    public function save(Request $request)
    {

        try {
            $params = $request->all();
            $rules = [
                'num' => 'integer',
                "rights_id" => 'required|integer',
                "id" => 'required|integer',
                "desc" => 'required|string',
            ];
            $num = $params['num'] ?? 0;
            $brandId = $params['id'];
            $desc = $params['desc'];
            $rightsId = $params['rights_id'];

            //校验参数
            $res_msg = Common::validatorRule($rules, $params);
            if ($res_msg !== true) {
                throw new Exception($res_msg);
            }

            //数量型需要在修改的基础上加上等级权益数量

            $brandInfo = Brand::getBrandInfoById($brandId);
            if (empty($brandInfo)) {
                throw new \Exception('品牌不存在');
            }

            $levelRightsNum = 0;

            $rightsType = BrandRightsSourceService::getRightsTypeById($rightsId);
            if ($rightsType == BrandRightsSource::RIGHTS_TYPE_NUM) {
                $levelRightsCfgInfo = BrandLevelRightsConfig::dataSelectInfo(
                    [
                        'level' => $brandInfo['level'],
                        'rights_source_id' => $rightsId,
                        'status' => BrandLevelRightsConfig::STATUS_NORMAL
                    ]
                );
                if (!empty($levelRightsCfgInfo)) {
                    $num = $num + $levelRightsCfgInfo['rights_data'];
                    $levelRightsNum = $levelRightsCfgInfo['rights_data'];
                }
                //数量不限情况处理
                $num = $num >= BrandRightsSource::COUNT_UNLIMIT ? BrandRightsSource::COUNT_UNLIMIT : $num;

            }

            $params = [
                $brandId,
                $params['rights_id'],
                Admin::user()->id,
                $num,
                $desc,
                $levelRightsNum
            ];
            BrandEquityVerificationService::addRightsNumForOp(...$params);
            BrandRightsAllService::checkBrandRightsEsCache(0, $brandId, $rightsId);
            $success = new MessageBag([
                'title' => '添加成功',
            ]);

        } catch (Exception $e) {
            $error = new MessageBag([
                'title' => $e->getMessage(),
            ]);
            return back()->with(compact('error'))->withInput();

        }
        return redirect('/admin/BrandRights/brandSource/' . $brandId)->with(compact('success'));
    }


    /**
     * 审核
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function audit(Request $request): JsonResponse
    {
        try {
            $params = $request->all();
            $rule = [
                'id' => 'required|int',
                'state' => 'required|int',
            ];
            $validator_msg = Common::validatorRule($rule, $params);
            if ($validator_msg !== true) {
                throw  new Exception($validator_msg);
            }
            $admin_id = Admin::user()->id;
            $where['id'] = $params['id'];
//            $data['admin_id'] = $admin_id;
            $data['rights_status'] = $params['state'];

            BrandRightsAll::updateData($data, $where);

            $info = BrandRightsAll::getInfo($where);
            $brandId = $info['brand_id'];
            $rightsId = $info['rights_source_id'];
            BrandRightsAllService::checkBrandRightsEsCache(0, $brandId, $rightsId);

            $success = [
                'title' => '操作成功',
                'code' => 1,
            ];
        } catch (\Exception $e) {
            $success = [
                'title' => '操作失败,' . $e->getMessage(),
                'msg' => '信息：' . $e->getFile() . $e->getLine(),
                'code' => 0,
                'status' => false,
            ];
        }

        return response()->json($success);

    }


    private function auditScript()
    {
        return <<<SCRIPT
        $('.edit-pass-data').unbind('click').click(function(){
            var id= $(this).data('id');
            var state=$(this).data('state');
            let url = '/admin/BrandRights/brandSource/audit'
            let params = {id:id,state:state}
            swal({
                    title: "确认提交吗？",
                    type: "warning",
                    showCancelButton: true,
                    confirmButtonColor: "#DD6B55",
                    confirmButtonText: "确认",
                    showLoaderOnConfirm: true,
                    cancelButtonText: "取消",
                    preConfirm: function() {
                    //ajax
                        $.ajax({
                            method: 'post',
                            url: url,
                            data: params,
                            success: function (e) {
                                if (e.code == 1) {
                                swal({
                                    title: e.title,
                                    type: "warning",
                                });
                                    setTimeout(function () {
                                        $.pjax.reload('#pjax-container');
                                    }, 1000);
                                } else {
                                    toastr.error(e.title, null, {
                                        timeOut : 3000
                                    }); 
                                }
                            }
                        });
                    //ajax-end
                    }
            });
        });
       
SCRIPT;
    }

}